import 'package:flutter/material.dart';
import 'package:flutter_app/domain/feed.dart';
import 'package:flutter_app/constant/constant.dart';
import 'package:flutter_app/interface/base_loading_view.dart';
import 'package:flutter_app/presenter/worm/worm_presenter.dart';
import 'package:flutter_app/widget/toast.dart';
import 'package:flutter_app/utils/text_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_app/page/worm/worm_image.dart';
import 'package:flutter_app/page/worm/worm_personal.dart';
import 'package:flutter_app/page/worm/worm_image_grid.dart';

/// 图虫
class WormPage extends StatefulWidget {
  /// 标题
  final String title;

  /// 构造方法
  WormPage({Key key, @required this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() => WormPageState();
}

/// 图虫状态
class WormPageState extends BaseLoadingView<WormPage> {
  /// 主持人
  WormPresenter presenter = WormPresenter();

  /// 数据列表
  List<FeedItem> list = List();

  /// 列表滚动控制器
  ScrollController _controller = ScrollController();

  @override
  void initState() {
    // 绑定视图
    this.presenter.attchView(this);
    super.initState();
    // 监听界面绘制完成
    // 加载数据
    WidgetsBinding.instance
        .addPostFrameCallback((callback) => presenter.loadData());
    // 上滑加载更多, 设置监听
    _controller.addListener(() {
      // 判断当前位置像素是否为最大像素
      if (this._controller.position.pixels ==
          this._controller.position.maxScrollExtent) {
        print('滑动到了底部');
        this.presenter.loadMoreData();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    // 销毁 ListView 控制器
    this._controller.dispose();
    // 解除绑定
    this.presenter.detachView();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: RefreshIndicator(
      onRefresh: this.presenter.onRefresh, // 下拉刷新
      child: Container(
        color: Color(Constant.GREY_300),
        child: ListView.builder(
          itemCount: list.length, // 数据长度
          itemBuilder: this._renderRow, // 渲染条目
          controller: this._controller, // 控制器
        ),
      ),
    ));
  }

  /// 绘制列表条目
  /// @param context 上下文
  /// @param index 条目标记
  Widget _renderRow(BuildContext context, int index) {
    FeedItem item = list[index];
    return Card(
      elevation: 5.0,
      color: Colors.white,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(10))),
      margin: EdgeInsets.all(10),
      child: Container(
        margin: EdgeInsets.all(5),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            this._renderHeader(item.site.name, item.site.icon,
                item.site.followers, item.site.url),
            this._renderContent(item.content),
            this._renderImage(
                item.site.name, index, item.imageCount, item.images),
            this._renderFooter(item.favorites, item.comments)
          ],
        ),
      ),
    );
  }

  @override
  void onNotNetwork() {
    Toast.show('请检查网络后重试!');
  }

  /// 加载最新数据
  /// @param feed 信息对象
  void onLoadFeed(Feed feed) {
    print('onLoadFeed: feed');
    // 遍历去重
    feed.feedList.forEach((FeedItem newItem) {
      // 标记是否包含
      bool isContain = false;

      for (var oldItem in this.list) {
        // 判断文章 ID 是否相同
        if (oldItem.postId == newItem.postId) {
          // 如果相同设置为 true
          isContain = true;
          break;
        }
      }
      // 如果不包含，则加入
      if (!isContain) {
        setState(() {
          this.list.insert(0, newItem);
        });
      }
    });
    print('刷新：${this.list.length}');
    // this.list = feed.feedList;
  }

  void onLoadMoreFeed(Feed feed) {
    print('onLoadMoreFeed: feed');
    setState(() {
      // 遍历去重
      feed.feedList.forEach((FeedItem newItem) {
        // 标记是否包含
        bool isContain = false;

        for (var oldItem in this.list) {
          // 判断文章 ID 是否相同
          if (oldItem.postId == newItem.postId) {
            // 如果相同设置为 true
            isContain = true;
            break;
          }
        }
        // 如果不包含，则加入
        if (!isContain) {
          setState(() {
            // this.list.insert(0, newItem);
            // 添加新数据
            this.list.add(newItem);
          });
        }
      });
      print('加载更多: ${this.list.length}');
    });
  }

  /// 绘制头
  /// @param name 作者名称
  /// @param icon 头像链接
  /// @param followers 关注数
  /// @param url 作者主页
  Widget _renderHeader(String name, String icon, int followers, String url) {
    // 粉丝字符串
    String followText = followers > 10000
        ? '${(followers / 10000).round()} 万粉丝'
        : '$followers 粉丝';
    return Container(
      // color: Colors.grey,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  InkWell(
                      onTap: () => Navigator.of(context).push(MaterialPageRoute(
                          builder: (context) => WormPersonalPage(name, url))),
                      child: Container(
                        width: 30,
                        height: 30,
                        margin: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                            image: DecorationImage(
                                image: NetworkImage(icon), fit: BoxFit.cover),
                            shape: BoxShape.circle),
                      ) // 圆形头像
                      )
                ],
              )),
          Expanded(
            flex: 3,
            child: Text(name), // 作者名
          ),
          Expanded(
              flex: 1,
              child: Container(
                  margin: EdgeInsets.only(right: 5),
                  alignment: Alignment.bottomRight,
                  child: Text(followText)) // 粉丝数量,
              )
        ],
      ),
    );
  }

  /// 绘制内容
  Widget _renderContent(String content) {
    // 判断文本是否为空
    if (TextUtil.isEmpty(content)) {
      return Container(width: 0, height: 0);
    } else {
      return Container(
        padding: EdgeInsets.all(10),
        margin: EdgeInsets.only(left: 10),
        child: Text(
          content,
          softWrap: true,
          overflow: TextOverflow.fade,
          maxLines: 10,
          style: TextStyle(fontFamily: Constant.FONT, fontSize: 16),
        ),
      );
    }
  }

  /// 绘制图片
  /// @param name 作者名称
  /// @param index 条目标识
  /// @param imageCount 图片数目
  /// @param images 图片列表
  Widget _renderImage(
      String name, int index, int imageCount, List<ImageDetail> images) {
    if (imageCount > 0) {
      return Container(
          padding: EdgeInsets.all(10),
          child: InkWell(
              onTap: () => Navigator.of(context).push(MaterialPageRoute(
                  builder: (context) => WormImagePage(
                      tag: 'image$index',
                      url: presenter.getImageUrl(
                          images[0].userId, images[0].imgId)))),
              onLongPress: () => Navigator.of(context).push(MaterialPageRoute(
                  builder: (context) =>
                      WormImageGridPage(name, imageCount, images, presenter))),
              child: Hero(
                tag: 'image$index', // Hero TAG 唯一
                child: CachedNetworkImage(
                  errorWidget: (context, url, error) => Icon(Icons.error),
                  placeholder: (context, url) => CircularProgressIndicator(),
                  imageUrl:
                      presenter.getImageUrl(images[0].userId, images[0].imgId),
                ), // 图片缓存
              ) // 跳转之后的页面要存在一个 Hero, 与这个 Hero 的 TAG 与之对应
              ));
    } else {
      return Container(width: 0, height: 0);
    }
  }

  /// 绘制尾部
  /// @param favorites 喜欢人
  /// @param comments 评论数
  Widget _renderFooter(int favorites, int comments) {
    return Container(
      height: 30,
      // color: Colors.green,
      child: Row(
        children: <Widget>[
          Expanded(flex: 3, child: Container()),
          Expanded(
              flex: 1,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Icon(
                        Icons.comment,
                        color: Colors.blueGrey,
                      ),
                      Text('10')
                    ],
                  ),
                  Row(
                    children: <Widget>[
                      Icon(
                        Icons.favorite,
                        color: Colors.red,
                      ),
                      Text('10')
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.only(right: 5),
                  )
                ],
              ))
        ],
      ),
    );
  }
}
